#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : jeffzhang
# @Time    : 2018/04/03
# @File    : vulnerability_plugin.py
# @Desc    : ""


import os
import re
import sys
from InsectsAwake.views.lib.mongo_db import connectiondb, db_name_conf
from flask import Flask

app = Flask(__name__)
plugin_db = db_name_conf()['plugin_db']


def get_plugin_re(plugin_filename):
    name_pattern = re.compile(r'name\s*=\s*[\'\"\[](.*)[\'\"\]]')
    author_pattern = re.compile(r'author\s*=\s*[\'\"\[](.*)[\'\"\]]')
    vuldate_pattern = re.compile(r'vulDate\s*=\s*[\'\"\[](.*)[\'\"\]]')
    appname_pattern = re.compile(r'appName\s*=\s*[\'\"\[](.*)[\'\"\]]')
    vultype_pattern = re.compile(r'vulType\s*=\s*[\'\"\[](.*)[\'\"\]]')
    appversion_pattern = re.compile(r'appVersion\s*=\s*[\'\"\[](.*)[\'\"\]]')
    plugin_data = open(plugin_filename, 'r').read()
    try:
        plugin_name = name_pattern.findall(plugin_data)
        plugin_author = author_pattern.findall(plugin_data)
        plugin_vuldate = vuldate_pattern.findall(plugin_data)
        plugin_appname = appname_pattern.findall(plugin_data)
        plugin_vultype = vultype_pattern.findall(plugin_data)
        plugin_appversion = appversion_pattern.findall(plugin_data)
        plugin_info = {
            "plugin_filename": plugin_filename,
            "plugin_name": plugin_name[0],
            "plugin_author": plugin_author[0],
            "plugin_vuldate": plugin_vuldate[0],
            "plugin_appname": plugin_appname[0],
            "plugin_vultype": plugin_vultype[0],
            "plugin_appversion": plugin_appversion[0],
        }
        return plugin_info
    except Exception as e:
        print(e)
        pass


def local_install():
    print("[*]扫描插件初始化...")
    connectiondb(plugin_db).drop()
    path = os.getcwd() + '/pocsuite_plugin/'
    files = os.listdir(path)
    for file_name in files:
        plugin_info = get_plugin_re(path + file_name.strip())
        if plugin_info is None:
            pass
        else:
            db_insert = connectiondb(plugin_db).insert_one(plugin_info).inserted_id
    print("[*]初始化完成!")


if __name__ == "__main__":
    local_install()
